package com.maxima.maximaAttendance.reports;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DateFormatSymbols;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;



public class ExportReports extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	DateFormatSymbols dfs = new DateFormatSymbols();
	String[] months = dfs.getMonths();
    public ExportReports() {
        super();
    }

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String month = request.getParameter("month");
		String year = request.getParameter("year");
		
		if (month != null && year != null)
		{	
			List<File> files = new Report().getReportFiles(month, year);
			export(response, files,months[Integer.parseInt(month) - 1] + "_" + year);
		}
		
		
	}
	
	public void export(HttpServletResponse response,  List<File> files, String filename) throws IOException {
		
		File tmpDir = getNewTmpDir();
		File zipFile = new File(tmpDir, UUID.randomUUID().toString());
		
		ZipUtils.createZip(files, zipFile);
		try {
			writeFileToOutput(response, filename, zipFile);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		files.add(zipFile);
		cleanUp(tmpDir, files);
	}
	private File getNewTmpDir() {
		File tmpDir = new File(System.getProperty("java.io.tmpdir"), UUID
				.randomUUID().toString());
		tmpDir.mkdir();
		return tmpDir;
	}
	private void cleanUp(File folder, List<File> files) {
		for (File file : files) {
			file.delete();
		}
		if(folder!=null) {
			folder.delete();
		}
	}
	private void writeFileToOutput(HttpServletResponse response, String filename,
			File zipFile) throws Exception {
		response.setContentLength((int) zipFile.length());

		response.setHeader(
				"Content-Disposition",
				"attachment; filename=\""+filename+".zip\"");

		InputStream inStream = null;
		OutputStream outStream = null;

		try {
			inStream = new FileInputStream(zipFile);
			outStream = response.getOutputStream();
			IOUtils.copy(inStream, outStream);

		} catch (Exception e) {
			System.out.println("Error");
			throw e;

		} finally {
			try {
				if (inStream != null)
					inStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			try {
				if (outStream != null)
				{
					outStream.flush();
					outStream.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}
